"""
@Project:p8_syl_flask
@File:oauth_user.py
@Author:郑凯乐
@Date:18:43
"""
import time
import json
import hmac
import urllib
from urllib.parse import parse_qs, urlencode
import base64
import requests
from flask import Blueprint
from flask_restful import Api,Resource,reqparse
from common.utils.my_output_json import custom_output_json
from common.models.user import OauthUser,UserModels
from werkzeug.security import check_password_hash
from common.models import db
from common.utils.jwt_utils import _generate_token
oauth_user_bp = Blueprint('oauth_user',__name__,url_prefix='/oauth')
# 创建蓝图的主入口
api = Api(oauth_user_bp)

# 统一后端返回给前端的数据结构
@api.representation('application/json')
def output_json(data, code,headers=None):
    resp = custom_output_json(data, code)
    return resp
# 钉钉第三方登录
class DingDingResource(Resource):

    def get_dingding_user(self,code):
        """获取扫码登录的用户信息"""
        # 2. 构建三个参数的值
        appid = "dingoajf8cqgyemqarekhr"
        appSecret = 'Fcah25vIw-koApCVN0mGonFwT2nSze14cEe6Fre8i269LqMNvrAdku4HRI2Mu9VK'
        timestamp = str(int(time.time() * 1000))
        # .digest()获取hash对象的值
        signature = base64.b64encode(
            hmac.new(appSecret.encode('utf-8'), timestamp.encode('utf-8'), digestmod="sha256").digest())

        base_url = "https://oapi.dingtalk.com/sns/getuserinfo_bycode?signature="
        # 拼接url
        url = base_url + urllib.parse.quote(signature.decode('utf-8')) + "&timestamp="+timestamp + "&accessKey=" + appid
        data = json.dumps({'tmp_auth_code':code})
        # 发起请求
        try:
            resp = requests.post(url, data, headers={'Content-Type': 'application/json'})
            print("resp>>>", resp.json())

        except Exception as e:
            # 根据code 获取用户信息失败
            return {'code':500, "message":'post 获取钉钉用户信息失败'}

        user_info = resp.json()
        if user_info['errcode'] != 0:
            # 获取当前登录的而用户信息失败
            return {'code': 500, "message": '根据code获取钉钉用户信息失败'}
        # 把用户信息转换成dict
        user_info_dict = user_info['user_info']
        return user_info_dict
    def get(self):
        """
        1.获取code值
        2. 构建accessKey(应用的AppKey)
         timestamp，(当前的时间戳，是单位毫秒)
         signature:(appSecret计算出来的签名值)
         三个参数的值
        3. 发起请求：
        post https://oapi.dingtalk.com/sns/getuserinfo_bycode?accessKey=ACCESS_KEY&timestamp=TIMESTAMP&signature=SIGNATURE
        :return: userInfo
        """
        parser = reqparse.RequestParser()
        parser.add_argument('code')
        args = parser.parse_args()
        # 1.获取code值
        code = args.get('code')
        # 发起请求，获取当前登录的用户信息
        user_info = self.get_dingding_user(code)
        # 根据钉钉的用户信息获取钉钉的openid
        openid = user_info['openid']
        # 获取openid 成功， 从oauth_user表查看当前钉钉用户是否和网站的用户绑定过
        oauth_user = OauthUser.query.filter_by(uid=openid).first()
        # 存在，说明绑定过
        if oauth_user:
            # 获取绑定的用户信息
            user = UserModels.query.filter_by(uid=oauth_user.user).first()
            # TODO 添加token
            # payload = {"uid": user.uid}
            # token = _generate_token(payload)
            return {'code':200,"account":user.account, 'uid':user.uid,}
        # 不存在没绑定
        else:
            return {"message":"没有绑定用户，请先绑定",'uid':openid}
# 钉钉绑定用户
class DingdingBindUser(Resource):
    def post(self):
        """绑定用户"""
        #思路分析
        """
        1.获取用户信息：用户名，密码，uid
        2.判断用户是否存在
            1.存在：
                校验密码
                直接绑定    
            2.不存在：
                去注册
        """
        parser = reqparse.RequestParser()
        parser.add_argument('account')
        parser.add_argument('password')
        parser.add_argument('unid')
        args = parser.parse_args()
        account = args.get('account')
        pwd = args.get('password')
        unid = args.get('unid')
        #判断用户是否存在
        user = UserModels.query.filter_by(account=account).first()
        if not user:
            #此时用户不存在
            return {"message":"用户未注册，请先注册","code":400}
        #用户存在，校验密码
        else:
            rest = check_password_hash(user.password,pwd)
            if not rest:
                #密码错误
                return {"messagr":400}
            else:
                #密码正确，进行绑定=添加数据
                user_ = OauthUser(uid=unid,user=user.uid,oauth_type="dingding")
                db.session.add(user_)
                db.session.commit()
                #TODO 添加token
                data_ = {
                    "account":user.account,
                    "token":"hgxxfxbxx",
                    "uid":user.uid
                }
                return {"message":"绑定成功","code":200,"data":data_}

class OauthWeiboLogin(Resource):
    def get_weibo_user(self, code):
        data_ = {
            "client_id": "2775107052",
            "client_secret": "718b38b04fc387700cc1595b30875b19",
            "grant_type": "authorization_code",
            "redirect_uri": "http://127.0.0.1:8080/weibo",
            "code": code,
        }
        base_url = "https://api.weibo.com/oauth2/access_token"
        try:
            resp = requests.post(url=base_url, data=data_).json()
            print("=======>resp", resp)
        except Exception as e:
            return {"message": "获取微博用户信息失败", "code": 400}

        if not resp["access_token"]:
            return {"message": "根据code获取钉钉用户信息失败", "code": 400}
        else:
            user_dict = resp
            return user_dict

    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument("code")
        args = parser.parse_args()
        code = args["code"]
        print("------->微博的code", code)

        user_dict = self.get_weibo_user(code)
        print("======>user_dict", user_dict)
        access_token = user_dict["access_token"]
        print("------>access_token", access_token)
        oauth_user = OauthUser.query.filter_by(uid=access_token, oauth_type="weibo").first()
        print("------>oauth_user", oauth_user)
        if oauth_user:
            user = UserModels.query.filter_by(uid=oauth_user.user).first()
            payload = {"uid": user.uid}
            token = _generate_token(payload)
            data_ = {
                "account": user.account,
                "id": user.uid,
                "token": token
            }
            return {"message": "登录成功", "code": 200, "data": data_}
        else:
            return {"message": "用户没有绑定，请先绑定", "code": 500, "uid": access_token}

class WeiboBindUser(Resource):
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument("account")
        parser.add_argument("password")
        parser.add_argument("unid")
        args = parser.parse_args()
        account = args["account"]
        password = args["password"]
        unid = args["unid"]
        print("------->unid", unid)
        user = UserModels.query.filter_by(account=account).first()
        if not user:
            return {"message": "用户未注册，请先注册", "code": 400}

        else:
            if not check_password_hash(user.password, password):
                return {"message": "密码错误", "code": 400}
            else:
                oauth_user = OauthUser(uid=unid, user=user.uid, oauth_type="weibo")
                db.session.add(oauth_user)
                db.session.commit()
                payload = {"uid": user.uid}
                token = _generate_token(payload)
                data_ = {
                    "uid": user.uid,
                    "account": user.account,
                    "token": token,
                }
                return {"message": "绑定成功", "code": 200, "data": data_}


api.add_resource(DingDingResource,'/dingding')
api.add_resource(DingdingBindUser,'/dingding/bind')
api.add_resource(WeiboBindUser, "/weibo/bind")
api.add_resource(OauthWeiboLogin, "/weibo")
